package tt.dz.egobus.api.util;

import org.springframework.beans.BeanUtils;
import tt.dz.egobus.api.exception.ResponseException;
import tt.dz.egobus.bean.CommonStatus;
import tt.dz.egobus.servicemanager.util.ReflectionUtils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Anson
 * @date 17-3-15
 * @name 返回帮助类
 * @since 1.0.1
 */
public final class ResponseHelper {

    /**
     * 属性拷贝
     *
     * @param s
     * @param t
     * @param <S>
     * @param <T>
     * @return
     */
    public static final <S, T> T copy(S s, T t) {
        BeanUtils.copyProperties(s, t);
        return t;
    }

    /**
     * 属性集合拷贝,必须提供默认构造器
     *
     * @param sList
     * @param tClass
     * @param <S>
     * @param <T>
     * @return
     */
    public static final <S, T> List<T> copy(List<S> sList, Class<T> tClass) {
        if (null == sList || sList.isEmpty()) {
            return new ArrayList<T>(0);
        }
        List<T> list = new ArrayList<T>(sList.size());
        T t = null;
        for (S s : sList) {
            t = ReflectionUtils.instance(tClass);
            if (t == null) {
                throw new ResponseException(CommonStatus.RPC_SYSTEM_CODE_ERROR);
            }
            t = copy(s, t);
            list.add(t);
        }
        return list;
    }

    /**
     * 属性数组拷贝,必须提供默认构造器
     *
     * @param sArray
     * @param tClass
     * @param <S>
     * @param <T>
     * @return
     */
    public static final <S, T> T[] copy(S[] sArray, Class<T> tClass) {
        if (null == sArray || sArray.length == 0) {
            return null;
        }
        List<T> list = new ArrayList<T>(sArray.length);
        T t = null;
        @SuppressWarnings("unchecked")
        T[] tarray = (T[]) Array.newInstance(tClass, sArray.length);
        S s = null;
        for (int i = 0; i < sArray.length; i++) {
            s = sArray[i];
            t = ReflectionUtils.instance(tClass);
            if (t == null) {
                throw new ResponseException(CommonStatus.RPC_SYSTEM_CODE_ERROR);
            }
            tarray[i] = copy(s, t);
        }


        return tarray;
    }

}
